package com.muyu.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.muyu.common.core.domain.R;
import com.muyu.common.core.exception.ServiceException;
import com.muyu.product.domain.ProductSku;
import com.muyu.product.domain.pojo.ProductInfoPO;
import com.muyu.product.domain.req.*;
import com.muyu.product.domain.vo.ProductInfoVo;
import com.muyu.product.mapper.ProductMapper;
import com.muyu.product.service.ProductService;
import com.muyu.product.until.ProductConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ProductServiceImpl
 * @Description 描述
 * @Author ShiYu.Cui
 * @Date 2024/3/26 20:32
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    /**
     * 添加
     * @param productInfoReq
     */
    @Override
    @Transactional
    public void saveOrUpdate(ProductInfoReq productInfoReq) {
      //参数校验
        //checkParams(productInfoReq);
        if(productInfoReq.getId()==null){
            // 添加优惠表
            insertSpecialOffers(productInfoReq);
            //添加商品信息表
            insertProductInfo(productInfoReq);
            //添加sku表
            insertSku(productInfoReq);
        }else{
            //修改优惠表
            updateSpecialOffers(productInfoReq);
            //修改商品信息表
            updateProductInfo(productInfoReq);
            //修改sku表
            updateSku(productInfoReq);
        }

    }


    /**
     * 修改商品信息
     * @param productInfoReq
     */
    private void updateProductInfo(ProductInfoReq productInfoReq) {
        // 更新产品基本信息
        Integer updateProductResult = productMapper.updateProductInfo(productInfoReq);
        if (updateProductResult <= 0) {
            log.error("修改商品信息失败");
            throw new ServiceException("修改商品信息失败");
        }
    }

    /**
     * 修改sku
     * @param productInfoReq
     */
    private void updateSku(ProductInfoReq productInfoReq) {

    }

    /**
     * 修改优惠表
     * @param productInfoReq
     */
    private void updateSpecialOffers(ProductInfoReq productInfoReq) {

    }

    private void insertSpecialOffers(ProductInfoReq productInfoReq) {
        if(productInfoReq.getOffersType()==1){
            //添加特惠促销
            SpecialOffersReq specialOffers = productInfoReq.getSpecialOffersReq();
            productMapper.inertSpecialOffers(specialOffers);
            productInfoReq.setOffersId(specialOffers.getId());

        }
        if(productInfoReq.getOffersType() == 2){
            //添加会员价格
            ShopMemberReq shopMemberReq = productInfoReq.getShopMemberReq();
            productMapper.insertShopMember(shopMemberReq);
            productInfoReq.setOffersId(shopMemberReq.getId());

        }
    }

    @Override
    public R<List<ProductInfoPO>> productList(ProductInfoVo productInfoVo) {
        List<ProductInfoPO> list=productMapper.productList(productInfoVo);
        return R.ok(list);
    }


    /**
     * 添加sku
     * @param productInfoReq
     */
    private void insertSku(ProductInfoReq productInfoReq) {
        //创建stuAttr集合
        ArrayList<ProductSku> skus = new ArrayList<>();
        //获取sku基本信息
        List<ProductSkuReq> productSkuList = productInfoReq.getProductSkuList();
        for (ProductSkuReq req : productSkuList) {
            req.put("productId",productInfoReq.getId());
            req.put("bgImg",productInfoReq.getBgImg());
        }
        Integer i = productMapper.insertSku(productSkuList);
        if(i<=0){
            log.error("添加商品sku失败");
            throw new ServiceException("添加商品sku："+productInfoReq.getProductSkuList()+"有误");
        }
        //创建stuAttr集合
        ArrayList<ProductSkuAttrReq> attrs = new ArrayList<>();
        productSkuList.forEach(productSkuReq -> {
            //赋值商品id
            productSkuReq.setId(productSkuReq.getId());
            //从继承的map中获取属性值
            ProductSku productSku= JSONObject.parseObject(JSONObject.toJSONString(productSkuReq), ProductSku.class);
            //将productSku转为HashMap 做key去重
            HashMap hashMap = JSONObject.parseObject(JSONObject.toJSONString(productSku), HashMap.class);
            Set setReqKey = productSkuReq.keySet();
            Set setKey = hashMap.keySet();
            //去重
            Set set=setReqKey;
            //剩下的为规格值
            set.removeAll(setKey);
            set.forEach(key ->{
                ProductSkuAttrReq productSkuAttrReq = new ProductSkuAttrReq();
                productSkuAttrReq.setSkuId(productSku.getId());
                productSkuAttrReq.setAttrId(Integer.valueOf(key.toString()));
                productSkuAttrReq.setAttrValueId(Integer.valueOf(key.toString()));
                productSkuAttrReq.setFlag(ProductConstants.IS_FLAG);
                attrs.add(productSkuAttrReq);
            });

        });
        log.info("sku的规格详情：{}",JSONObject.toJSONString(attrs));
        Integer i2= productMapper.insertSkuAttr(attrs);
        if(i2<=0){
            log.error("添加商品sku属性失败");
            throw new ServiceException("添加商品sku属性失败"+productInfoReq.getProductName()+"有误");
        }
    }



    /**
     * 添加商品信息
     * @param productInfoReq
     */
    private void insertProductInfo(ProductInfoReq productInfoReq) {
        Integer i = productMapper.insertProduct(productInfoReq);
        if ( i <= 0) {
            log.error("添加商品失败");
            throw new ServiceException("商品：" + productInfoReq.getProductName() + "有误");
        }
    }


//    @SneakyThrows
//    private void checkParams(ProductInfoReq productInfoReq) {
//        long startTime = System.currentTimeMillis();
//        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//            // 异步校验商品分类是否存在
//            CompletableFuture<Void> classifyFuture = CompletableFuture.runAsync(() -> {
//                ProductClassify productClassify = productMapper.selectCountByType(productInfoReq.getProductClassIfyId());
//                if (productClassify == null) {
//                    log.error("商品分类不存在！");
//                    throw new ServiceException("商品分类id：" + productInfoReq.getProductClassIfyId() + "不存在");
//                }
//            });
//
//            // 异步校验商品品牌是否存在
//            CompletableFuture<Void> brandFuture = CompletableFuture.runAsync(() -> {
//                ProductBrand brand = productMapper.getBrand(productInfoReq.getProductBrandId());
//                if (brand == null) {
//                    log.error("商品品牌不存在！");
//                    throw new ServiceException("商品品牌id：" + productInfoReq.getProductBrandId() + "不存在");
//                }
//            });
//
//            // 等待所有异步任务执行完成
//            CompletableFuture.allOf(classifyFuture, brandFuture).join();
//        });
//        // 等待所有异步任务执行完成
//        future.join();
//        long endTime = System.currentTimeMillis();
//        System.out.println(endTime - startTime);
//    }

    @Override
    public ProductInfoReq getProductDetailById(Integer id) {
        //构建返回结果集
        ProductInfoReq productInfoReq = new ProductInfoReq();
        //根据商品id查询商品表，获取商品基本信息
        productInfoReq=getBaseInfoById(id);
        //获取优惠信息
        setOffers(productInfoReq);
        //获取sku信息
        setSkuInfos(productInfoReq);

        return productInfoReq;
    }

    private void setSkuInfos(ProductInfoReq productInfoReq) {
        //构建结果集
        List<ProductSkuReq> result = new ArrayList<>();
        //查询商品sku集合
        List<ProductSku> skus = productMapper.getSkuById(productInfoReq.getId());
        if(skus==null ||skus.isEmpty()){
            log.debug("未找到与商品ID{}相关的sku信息",productInfoReq.getId());
            return;
        }
        //获取skuIds
        List<Long> skuIds = skus.stream().map(ProductSku::getId).collect(Collectors.toList());
        // 获取sku属性集合，并使用Map存储以加快查找速度
        Map<Long, List<ProductSkuAttrReq>> skuAttrMap = productMapper.getSkuAttrById(skuIds).stream()
                .collect(Collectors.groupingBy(ProductSkuAttrReq::getSkuId));
        if (skuAttrMap!=null){
            //构建sku信息
            skus.forEach(sku -> {
                ProductSkuReq productSkuReq = new ProductSkuReq();
                productSkuReq.put("id",sku.getId());
                productSkuReq.put("salePrice",sku.getSalePrice());
                productSkuReq.put("promotionPrice",sku.getPromotionPrice());
                productSkuReq.put("stock",sku.getStock());
                productSkuReq.put("stockAlert",sku.getStockAlert());
                productSkuReq.put("bgImg",sku.getBgImg());
                List<ProductSkuAttrReq> productAttrValueResponse=new ArrayList<>();
                List<ProductSkuAttrReq> skuAttrs=skuAttrMap.get(sku.getId());
                if(skuAttrs!=null){
                    for (ProductSkuAttrReq attr : skuAttrs) {
                        productAttrValueResponse.add(attr);
                    }
                    productSkuReq.put("productAttrValueResponse",productAttrValueResponse);
                }

                //设置sku属性
                result.add(productSkuReq);
            });
        }
        productInfoReq.setProductSkuList(result);
    }

    private void setOffers(ProductInfoReq productInfoReq) {
        //根据优惠type中的productId去对应的表查询优惠信息
        if(productInfoReq.getOffersType()==1){
            SpecialOffersReq specialOffersReq = productMapper.getSpecialOffers(productInfoReq.getOffersId());
            productInfoReq.setSpecialOffersReq(specialOffersReq);
            ShopMemberReq shopMember = new ShopMemberReq();
            shopMember.setGoldPrice(0.0);
            shopMember.setDiamondPrice(0.0);
            shopMember.setPlatinumPrice(0.0);
            productInfoReq.setShopMemberReq(shopMember);
        }
        if(productInfoReq.getOffersType()==2){
            ShopMemberReq shopMemberReq = productMapper.getShopMember(productInfoReq.getOffersId());
            productInfoReq.setShopMemberReq(shopMemberReq);
            SpecialOffersReq specialOffersReq = new SpecialOffersReq();
            specialOffersReq.setOffersPrice(0.0);
            specialOffersReq.setStartTime(new Date());
            specialOffersReq.setEndTime(new Date());
            productInfoReq.setSpecialOffersReq(specialOffersReq);
        }
    }

    private ProductInfoReq getBaseInfoById(Integer id) {
        ProductInfoReq productInfoReq=productMapper.getProductDetailById(id);
        return productInfoReq;
    }

}
